"""

"""

from kivymd.uix.card import MDCard
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.gridlayout import MDGridLayout
from kivymd.uix.label import MDLabel
from datetime import timedelta

class VideoInfoCard(MDCard):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.padding = "20dp"
        self.spacing = "15dp"
        self.elevation = 2
        self.size_hint_y = None
        self.height = "250dp"
        
        self._build_ui()
    
    def _build_ui(self):
        """"""
        # 
        title = MDLabel(
            text=" ",
            theme_text_color="Primary",
            font_style="H6",
            size_hint_y=None,
            height="40dp"
        )
        self.add_widget(title)
        
        # 
        self.info_grid = MDGridLayout(
            cols=2,
            spacing="10dp",
            size_hint_y=None,
            height="180dp",
            adaptive_height=True
        )
        self.add_widget(self.info_grid)
        
        # 
        self._init_info_items()
    
    def _init_info_items(self):
        """"""
        self.info_items = {
            'filename': self._create_info_item(" ", ""),
            'duration': self._create_info_item("⏱ ", "00:00:00"),
            'size': self._create_info_item(" ", "0 MB"),
            'format': self._create_info_item(" ", ""),
            'resolution': self._create_info_item(" ", ""),
            'fps': self._create_info_item(" ", "0 fps"),
            'audio_rate': self._create_info_item(" ", ""),
            'bitrate': self._create_info_item(" ", "")
        }
    
    def _create_info_item(self, label_text, value_text):
        """"""
        # 
        label = MDLabel(
            text=label_text,
            theme_text_color="Secondary",
            font_style="Caption",
            size_hint_y=None,
            height="30dp"
        )
        self.info_grid.add_widget(label)
        
        # 
        value = MDLabel(
            text=value_text,
            theme_text_color="Primary",
            font_style="Body2",
            size_hint_y=None,
            height="30dp"
        )
        self.info_grid.add_widget(value)
        
        return {'label': label, 'value': value}
    
    def update_video_info(self, video_info):
        """"""
        if not video_info:
            return
        
        # 
        filename = video_info.get('original_name', video_info.get('filename', ''))
        self.info_items['filename']['value'].text = filename
        
        # 
        duration = video_info.get('duration', 0)
        duration_str = str(timedelta(seconds=int(duration)))
        self.info_items['duration']['value'].text = duration_str
        
        # 
        file_size = video_info.get('file_size', 0)
        size_str = self._format_file_size(file_size)
        self.info_items['size']['value'].text = size_str
        
        # 
        format_name = video_info.get('format_name', '')
        self.info_items['format']['value'].text = format_name
        
        # 
        width = video_info.get('width')
        height = video_info.get('height')
        if width and height:
            resolution = f"{width}×{height}"
        else:
            resolution = ""
        self.info_items['resolution']['value'].text = resolution
        
        # 
        fps = video_info.get('fps', 0)
        if fps:
            fps_str = f"{fps:.1f} fps"
        else:
            fps_str = "N/A"
        self.info_items['fps']['value'].text = fps_str
        
        # 
        sample_rate = video_info.get('sample_rate')
        if sample_rate:
            audio_str = f"{sample_rate}Hz"
        else:
            audio_str = ""
        self.info_items['audio_rate']['value'].text = audio_str
        
        # 
        bit_rate = video_info.get('bit_rate')
        if bit_rate:
            bitrate_str = f"{int(bit_rate/1000)} kbps"
        else:
            bitrate_str = ""
        self.info_items['bitrate']['value'].text = bitrate_str
    
    def _format_file_size(self, size_bytes):
        """"""
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB", "TB"]
        i = 0
        while size_bytes >= 1024 and i < len(size_names) - 1:
            size_bytes /= 1024.0
            i += 1
        
        return f"{size_bytes:.1f} {size_names[i]}"
    
    def clear_info(self):
        """"""
        default_values = {
            'filename': "",
            'duration': "00:00:00",
            'size': "0 MB",
            'format': "",
            'resolution': "",
            'fps': "0 fps",
            'audio_rate': "",
            'bitrate': ""
        }
        
        for key, value in default_values.items():
            if key in self.info_items:
                self.info_items[key]['value'].text = value